﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using System.Data;
using System.Data.SqlClient;

namespace Data
{
    public class CardReaderData
    {
        Connect cn = new Connect();
        CardData cD = new CardData();

        public bool AcceptCard(CardsEntity cE)
        {
            int Npara = 1;
            string[] name = new string[Npara];
            object[] value = new object[Npara];
            name[0] = "@CardNo";
            value[0] = cE.CardNo;
            string sql = "dbo.CardsSelectByID";
            DataTable dt = cn.GetData(sql, name, value, Npara);

            if (dt != null && dt.Rows.Count == 1 && dt.Rows[0]["Status"].ToString() != "block")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool ValidatePIN(CardsEntity cE)
        {
            if (cE.PIN == cD.GetPIN(cE))
            {
                return true;
            }
            else
            {
                CardsEntity cdE = cD.CardsEntity(cE.CardNo);
                int Npara = 7;
                string[] name = new string[Npara];
                object[] value = new object[Npara];
                name[0] = "@CardNo"; value[0] = cdE.CardNo;
                name[1] = "@Status"; value[1] = cdE.Status;
                name[2] = "@AccountID"; value[2] = cdE.AccountID;
                name[3] = "@PIN"; value[3] = cdE.PIN;
                name[4] = "@StartDate"; value[4] = cdE.StartDate;
                name[5] = "@ExpiredDate"; value[5] = cdE.ExpiredDate;
                name[6] = "@Attempt"; value[6] = (cdE.Attempt + 1);
                string sql = "dbo.CardsUpDate";
                cn.NonQuery(sql, name, value, Npara);
                return false;
            }
        }

        public void SwallowCard(CardsEntity cE)
        {
            CheckAttempt(cE);
        }

        public void CheckAttempt(CardsEntity cE)
        {
            if (cD.GetAttempt(cE) >= 3)
            {
                cD.Block(cE);
            }
        }
    }
}
